package com.zxl.live.screen.screen.ui.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.zxl.live.screen.R;
import com.zxl.live.screen.model.TasksManager;
import com.zxl.live.screen.model.bean.DownloadBean;
import com.zxl.live.screen.screen.constant.ISharedPreferences;
import com.zxl.live.screen.screen.ui.helper.DataHelper;
import com.zxl.live.screen.screen.ui.helper.SuiScreenViewHelper;
import com.zxl.live.screen.screen.ui.helper.data.SuiScreenDataHelper;
import com.zxl.live.tools.base.ActivityLifecycle;
import com.zxl.live.tools.base.BaseAppCompatFragment;
import com.zxl.live.tools.tools.SpUtils;
import com.zxl.live.tools.track.StatisticsConstant;

import java.io.File;

/**
 * Created by Administrator on 2018/1/9.
 */
public class SuiScreenDetailFragment extends BaseAppCompatFragment implements SeekBar.OnSeekBarChangeListener, View.OnClickListener, TasksManager.OnDownloadStatusListener {

    private boolean mIsFailed;

    private int mPosition;

    private TextView mTipsView;

    private SeekBar mSeekBar;

    private View mLoadView, mSettingView;

    private SuiScreenDataHelper.DataType dataType;

    public void setPosition(int mPosition, SuiScreenDataHelper.DataType dataType) {
        this.mPosition = mPosition;
        this.dataType = dataType;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_sui_screen_detail, container, false);
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TasksManager.getInstance().addOnDownloadStatusListener(this);
        mTipsView = (TextView) view.findViewById(R.id.tv_time);
        mSeekBar = (SeekBar) view.findViewById(R.id.time_setting);
        mSeekBar.setOnSeekBarChangeListener(this);
        view.findViewById(R.id.btn_start).setOnClickListener(this);
        mLoadView = view.findViewById(R.id.loading);
        mSettingView = view.findViewById(R.id.settings);
        ImageView srcImage = (ImageView) view.findViewById(R.id.src);
        Glide.with(getContext()).load(SuiScreenDataHelper.getPreviewImage(dataType, mPosition)).into(srcImage);

        String url = DataHelper.getFirstDownloadUrl(dataType, mPosition);
        if (!TextUtils.isEmpty(url)) {
            if (DataHelper.hasDownloadFile(dataType, mPosition)) {
                mLoadView.setVisibility(View.GONE);
                mSettingView.setVisibility(View.VISIBLE);
            } else {
                TasksManager.getInstance().addTask(DownloadBean.createSuiBean(url, DataHelper.getFirstDownloadPath(dataType, mPosition)));
            }
        } else if (dataType == SuiScreenDataHelper.DataType.SYSTEM_ERROR) {
            mLoadView.setVisibility(View.GONE);
            mSettingView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mIsFailed && !DataHelper.hasDownloadFile(dataType, mPosition)) {
                mIsFailed = false;
                TasksManager.getInstance().addTask(DownloadBean.createSuiBean(DataHelper.getFirstDownloadUrl(dataType, mPosition), DataHelper.getFirstDownloadPath(dataType, mPosition)));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TasksManager.getInstance().removeOnDownloadStatusListener(this);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        mTipsView.setText(progress + "");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onClick(View v) {
        if (dataType == SuiScreenDataHelper.DataType.KUONGBU) {
            if (!SpUtils.obtain(ISharedPreferences.SP_DEFAULT_MAIN_PROCESS).getBoolean(ISharedPreferences.IS_SHOW_KONGBU_TIPS)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.tips);
                builder.setMessage(R.string.kongbu_tips);
                builder.setPositiveButton(R.string.ok_see, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SpUtils.obtain(ISharedPreferences.SP_DEFAULT_MAIN_PROCESS).save(ISharedPreferences.IS_SHOW_KONGBU_TIPS, true);
                        apply();
                    }
                });
                builder.show();
                return;
            }
        }
        apply();
    }

    private void apply() {
        SuiScreenViewHelper.sendSuiShow(mPosition, dataType, mSeekBar.getProgress());
        dataType.upload(getContext(), StatisticsConstant.Event.APPLY, mPosition + "");
        dataType.upload(getContext(), StatisticsConstant.Event.STATUS, mSeekBar.getProgress() + "");
        ActivityLifecycle.killSelf();
    }

    @Override
    public void onPause(BaseDownloadTask task) {
    }

    @Override
    public void onError(BaseDownloadTask task) {
        String url = task.getUrl();
        if (url.equals(DataHelper.getFirstDownloadUrl(dataType, mPosition))) {
            TasksManager.getInstance().addTask(DownloadBean.createSuiBean(DataHelper.getSecondDownloadUrl(dataType, mPosition), DataHelper.getSecondDownloadPath(dataType, mPosition)));
        } else if (url.equals(DataHelper.getSecondDownloadUrl(dataType, mPosition))) {
            mIsFailed = true;
            Toast.makeText(getContext(), R.string.error_net_work, Toast.LENGTH_SHORT).show();
        }
        try {
            dataType.upload(getContext(), StatisticsConstant.Event.DOWNLOAD_ERROR, new File(url).getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCompleted(BaseDownloadTask task) {
        String url = task.getUrl();
        if (url.equals(DataHelper.getFirstDownloadUrl(dataType, mPosition)) || url.equals(DataHelper.getSecondDownloadUrl(dataType, mPosition))) {
            mLoadView.setVisibility(View.GONE);
            mSettingView.setVisibility(View.VISIBLE);
            try {
                dataType.upload(getContext(), StatisticsConstant.Event.DOWNLOAD_SUCCESS, new File(url).getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onProgress(BaseDownloadTask task, int progress) {
    }
}
